package com.cloud.lawcase.api.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cloud.lawcase.api.bean.LawCauseExcuteType;
import com.cloud.lawcase.api.bean.LawCauseInterfaceSearchCriteria;
import com.cloud.lawcase.api.bean.LawCauseItem;
import com.cloud.lawcase.api.bean.PunishDetailsItemBean;
import com.cloud.lawcase.api.entity.TcAccessGlobalParams;
import com.cloud.lawcase.api.entity.TcDicLaw;
import com.cloud.lawcase.api.entity.TcDicLawExcuteType;
import com.cloud.lawcase.api.entity.TcDicLawItem;
import com.cloud.lawcase.api.entity.TcLawClDetail;
import com.cloud.lawcase.api.entity.TcLawRelCauseExcuteType;
import com.cloud.lawcase.api.entity.TcRelPunishUnitFunc;
import com.cloud.lawcase.api.entity.TcRelPunishUnitLevel;
import com.cloud.lawcase.api.mapper.TcAccessGlobalParamsMapper;
import com.cloud.lawcase.api.mapper.TcDicLawCauseMapper;
import com.cloud.lawcase.api.mapper.TcDicLawItemMapper;
import com.cloud.lawcase.api.mapper.TcLawClDetailMapper;
import com.cloud.lawcase.api.mapper.TcLawRelCauseExcuteTypeMapper;
import com.cloud.lawcase.api.mapper.TcRelPunishUnitFuncMapper;
import com.cloud.lawcase.api.mapper.TcRelPunishUnitLevelMapper;
import com.cloud.lawcase.api.service.LawCauseInterfaceService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import tk.mybatis.mapper.entity.Example;

@Service
@Transactional
public class LawCauseInterfaceServiceImpl implements LawCauseInterfaceService {

    @Autowired
    private TcAccessGlobalParamsMapper tcAccessGlobalParamsMapper;
    @Autowired
    private TcDicLawCauseMapper tcDicLawCauseMapper;
    @Autowired
    private TcDicLawItemMapper tcDicLawItemMapper;
    @Autowired
    private TcLawRelCauseExcuteTypeMapper tcLawRelCauseExcuteTypeMapper;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
	private TcRelPunishUnitFuncMapper tcRelPunishUnitFuncMapper;
	@Autowired
	private TcRelPunishUnitLevelMapper tcRelPunishUnitLevelMapper;
	@Autowired
	private TcLawClDetailMapper tcLawClDetailMapper;

    @Override
    public PageInfo<LawCauseItem> searhCausePageInfo(LawCauseInterfaceSearchCriteria criteria) {
        // 区域
        Example paramsExample = new Example(TcAccessGlobalParams.class);
        Example.Criteria paramsCriteria = paramsExample.createCriteria();
        paramsCriteria.andEqualTo("appId", criteria.getAppKey());
        paramsCriteria.andEqualTo("paramName", "law_region_id");
        List<TcAccessGlobalParams> params = tcAccessGlobalParamsMapper.selectByExample(paramsExample);
        if (null != params && params.size() > 0) {
            for (TcAccessGlobalParams p : params) {
                criteria.setRegionCodes(p.getParamValue());
            }
        }
        // 处罚类型
        PageInfo<LawCauseItem> pageInfo = PageHelper.startPage(criteria.getPageNum(), criteria.getPageSize())
                .doSelectPageInfo(() -> {
                    tcDicLawCauseMapper.searhCausePageInfo(criteria);
                });
        List<LawCauseItem> list = pageInfo.getList();
        List<Long> causeIds = new ArrayList<Long>();
        if (null != list && list.size() > 0) {
            for (LawCauseItem item : list) {
                causeIds.add(item.getCauseId());
            }
        }
        if(causeIds.size() > 0){
        	// 罚则
            List<TcDicLawItem> punishItems = tcDicLawItemMapper.listPunishItemByCauseIds(causeIds);
            // 违则
            List<TcDicLawItem> infergeItems = tcDicLawItemMapper.listInfringeItemByCauseIds(causeIds);
            // 处罚类别
            List<TcLawRelCauseExcuteType> excuteTypes = tcLawRelCauseExcuteTypeMapper.listExceuteTypeByCauseIds(causeIds);
            for (LawCauseItem item : list) {
                long causeId = item.getCauseId();
                for (TcDicLawItem pItem : punishItems) {
                    if (causeId == pItem.getCauseId()) {
                        item.setFzCode(pItem.getItemCode());
                        item.setFzItem(pItem.getItemContent());
                        item.setFzItemName(pItem.getItemName());
                        break;
                    }
                }
                for (TcDicLawItem pItem : infergeItems) {
                    if (causeId == pItem.getCauseId()) {
                    	item.setWzCode(pItem.getItemCode());
                        item.setWzItem(pItem.getItemContent());
                        item.setWzItemName(pItem.getItemName());
                        break;
                    }
                }
                for (TcLawRelCauseExcuteType type : excuteTypes) {
                    if (causeId == type.getCauseId()) {
                        LawCauseExcuteType p = new LawCauseExcuteType();
                        p.setExcuteTypeId(type.getExcuteTypeId());
                        p.setExcuteTypeName(type.getExcuteTypeName());
                        item.getPunishs().add(p);
                    }
                }
            }
            //自由裁量准则
            List<TcLawRelCauseExcuteType> punishTypes = tcLawRelCauseExcuteTypeMapper.listExceuteTypeByCauseIds(causeIds);
            List<TcRelPunishUnitFunc> unitFuncs = tcRelPunishUnitFuncMapper.listUnitFuncByCauseIds(causeIds);
    		List<TcRelPunishUnitLevel> unitLevels = tcRelPunishUnitLevelMapper.listUnitLevelByCauseIds(causeIds);
    		Example clDetailExample = new Example(TcLawClDetail.class);
    		Example.Criteria clDetailCriteria = clDetailExample.createCriteria();
    		clDetailCriteria.andIn("causeId", causeIds);
    		List<TcLawClDetail> clDetails = tcLawClDetailMapper.selectByExample(clDetailExample);
    		
            for (TcLawRelCauseExcuteType punish : punishTypes) {
            	StringBuilder punishTypeStr = new StringBuilder();
            	for(LawCauseItem item : list){
            		if (punish.getCauseId().equals(item.getCauseId())) {
        				// 处罚
        				PunishDetailsItemBean punishDetailItem = new PunishDetailsItemBean();
        				TcDicLawExcuteType excuteType = new TcDicLawExcuteType();
        				excuteType.setExcuteTypeId(punish.getExcuteTypeId());
        				excuteType.setExcuteTypeName(punish.getExcuteTypeName());
        				punishDetailItem.setPunishType(excuteType);
        				punishDetailItem.setSituationDesc(punish.getSituationDesc());

        				punishTypeStr.append(punish.getExcuteTypeName()).append(",");
        				// 职能部门
        				for (TcRelPunishUnitFunc func : unitFuncs) {
        					if (func.getCauseId().equals(item.getCauseId())
        							&& punish.getPunishId().equals(func.getPunishId())) {
        						punishDetailItem.getFuncUnits().add(func);
        					}
        				}
        				// 职能层级
        				for (TcRelPunishUnitLevel level : unitLevels) {
        					if (level.getCauseId().equals(item.getCauseId())
        							&& punish.getPunishId().equals(level.getPunishId())) {
        						punishDetailItem.getFuncLevels().add(level);
        					}
        				}
        				// 裁量明细
        				for (TcLawClDetail clDetail : clDetails) {
        					if (clDetail.getCauseId().equals(item.getCauseId())
        							&& punish.getPunishId().equals(clDetail.getPunishId())) {
        						if (clDetail.getTopUnit() == 1) {
        							clDetail.setTopUnitName("元");
        						} else if (clDetail.getTopUnit() == 2) {
        							clDetail.setTopUnitName("倍");
        						}
        						if (clDetail.getLowerUnit() == 1) {
        							clDetail.setLowerUnitName("元");
        						} else if (clDetail.getLowerUnit() == 2) {
        							clDetail.setLowerUnitName("倍");
        						}
        						punishDetailItem.getClDetails().add(clDetail);
        					}
        				}
        				item.getClDetail().add(punishDetailItem);
        			}
            	}
    		}
        }
        return pageInfo;
    }

    @Override
    public Map<String, Object> getInfoGeneral() {
        Map<String, Object> countMap = new HashedMap();

        try {
            String sql = "select\n" +
                    "  count(b.law_id) as count,\n" +
                    "  a.group_id as groupid,\n" +
                    "  a.group_name as groupname\n" +
                    "from\n" +
                    "  tc_dic_law_group a\n" +
                    "  left join tc_dic_law b on a.group_id = b.group_id \n" +
                    "where\n" +
                    "  a.senior_group_id = 1 \n" +
                    "group by\n" +
                    "  a.group_id,\n" +
                    "  a.group_name";
            List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);

            Long sum = new Long(0);
            for (Map<String, Object> item : list) {
                String name = "";
                int groupid = item.get("groupid") == null ? 0 : Integer.parseInt(item.get("groupid").toString());
                switch (groupid) {
                    case 2:
                        name = "law";
                        break;
                    case 132:
                        name = "administration";
                        break;
                    case 382:
                        name = "locality";
                        break;
                    case 383:
                        name = "department";
                        break;
                    case 884:
                        name = "government";
                        break;
                    default:
                        break;
                }
                Long count = item.get("count") == null ? 0 : Long.valueOf(item.get("count").toString());
                countMap.put(name, count);

                sum += count;
            }
            countMap.put("sum", sum);
        } catch (Exception e) {
        }

        return countMap;
    }

    @Override
    public List<Map<String, Object>> statCauseExcuteType() {
        List<Map<String, Object>> list = new ArrayList<>();

        try {
            String sql = "select\n" +
                    "  count(*) as count,\n" +
                    "  b.excute_type_name as name \n" +
                    "from\n" +
                    "  tc_dic_law_cause a\n" +
                    "  left join tc_dic_law_excute_type b on a.excute_type_id = b.excute_type_id \n" +
                    "group by\n" +
                    "  b.excute_type_id,\n" +
                    "  b.excute_type_name \n" +
                    "order by\n" +
                    "  b.excute_type_id";
            list = jdbcTemplate.queryForList(sql);
        } catch (Exception e) {
        }

        return list;
    }

    @Override
    public List<Map<String, Object>> getLawDomain() {
        List<Map<String, Object>> list = new ArrayList<>();

        try {
            String sql = "select\n" +
                    "  law_type_id as id,\n" +
                    "  law_type_name as name \n" +
                    "from\n" +
                    "  tc_dic_law_type\n" +
                    "where\n" +
                    "  senior_id = 0\n" +
                    "  and enable_flag = 1\n" +
                    "order by\n" +
                    "  display_order";
            list = jdbcTemplate.queryForList(sql);
        } catch (Exception e) {
        }

        return list;
    }

    @Override
    public List<Map<String, Object>> getLawCodeGroup() {
        List<Map<String, Object>> list = new ArrayList<>();

        try {
            String sql = "select\n" +
                    "  c.law_code as lawcode,\n" +
                    "  c.law_title as lawtitle,\n" +
                    "  d.group_id as groupid,\n" +
                    "  regexp_replace(d.group_name, '[(][0-9]*[)]', '') as groupname\n" +
                    "from\n" +
                    "  (\n" +
                    "  select\n" +
                    "    a.law_code,\n" +
                    "    a.law_title,\n" +
                    "    regexp_substr(b.group_code, '[0-9]*', 2, 3) as group_id \n" +
                    "  from\n" +
                    "    tc_dic_law a\n" +
                    "    left join tc_dic_law_group b on a.group_id = b.group_id \n" +
                    "  where\n" +
                    "    b.senior_group_id > 0 \n" +
                    "  ) as c,\n" +
                    "  (select * from tc_dic_law_group where senior_group_id = 1) as d \n" +
                    "where\n" +
                    "  c.group_id = d.group_id";
            list = jdbcTemplate.queryForList(sql);
        } catch (Exception e) {
        }

        return list;
    }

    @Override
    public List<TcLawRelCauseExcuteType> listExceuteTypeByCauseCode(List<String> causeCodes) {
        return tcLawRelCauseExcuteTypeMapper.listExceuteTypeByCauseCode(causeCodes);
    }

    @Override
    public List<TcLawClDetail> listClDetailByCauseCode(List<String> causeCodes) {
        List<Long> cids = tcLawClDetailMapper.listCauseIdByCauseCode(causeCodes);
        Example clDetailExample = new Example(TcLawClDetail.class);
        Example.Criteria clDetailCriteria = clDetailExample.createCriteria();
        clDetailCriteria.andIn("causeId", cids);
        List<TcLawClDetail> lawClDetails = tcLawClDetailMapper.selectByExample(clDetailExample);
        List<TcLawClDetail> clDetails = new ArrayList<>();
        // 裁量明细
        if (lawClDetails != null  && lawClDetails.size() > 0) {
            for (TcLawClDetail clDetail : lawClDetails) {
                if (clDetail.getTopUnit() == 1) {
                    clDetail.setTopUnitName("元");
                } else if (clDetail.getTopUnit() == 2) {
                    clDetail.setTopUnitName("倍");
                }
                if (clDetail.getLowerUnit() == 1) {
                    clDetail.setLowerUnitName("元");
                } else if (clDetail.getLowerUnit() == 2) {
                    clDetail.setLowerUnitName("倍");
                }
                clDetails.add(clDetail);
            }
        }
        return clDetails;
    }

	@Override
	public List<TcDicLaw> searchLaw(String title, int type) {
		return jdbcTemplate.query("select t1.law_id, t1.law_title from tc_dic_law t1 where t1.law_title like ? and t1.sx_id = 1 and exists (select t2.rel_id from tc_law_rel_cause_biz t2 where t1.law_id = t2.law_id and t2.biz_id = ?)limit 10", 
				new BeanPropertyRowMapper<TcDicLaw>(TcDicLaw.class), "%"+title+"%", type);
	}

	@Override
	public List<TcDicLawItem> searchLawItem(long lawId, int type) {
		return jdbcTemplate.query("select * from (select item_code, item_id, item_name from tc_dic_law_item t1 where t1.law_id = ? and "
				+ "exists (select * from tc_dic_law_cause t2 where t2.law_id = ? and t2.excute_type_id = 1 and t1.item_id = t2.item_id) union "
				+ "select item_code, item_id, item_name from tc_dic_law_item t1 where t1.law_id = ? and exists "
				+ "(select * from tc_law_rel_cause_law_item t2 where t2.law_id = ? and t1.item_id = t2.item_id and t2.item_type_id in(1,2))"
				+ ") t where exists (select * from tc_law_rel_cause_biz t2 where t.item_id = t2.item_id and t2.biz_id = ?) order by item_code", 
				new BeanPropertyRowMapper<TcDicLawItem>(TcDicLawItem.class), lawId, lawId, lawId, lawId, type);
	}
    @Override
    public List<LawCauseItem> listCasueIDByCauseCode(List<String> causeCodes) {
        return tcDicLawCauseMapper.listCasueIDByCauseCode(causeCodes);
    }
}
